<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2024-12-18 16:17:27
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2025-01-07 11:57:35
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\basicInformation\measurementUnits\components\addModifPop.vue
-->
<template>
  <pb-popup v-model="isShow" :title="`${unitForm.skuPackagingUnitId ? '编辑' : '新增'}计量单位`" @cancelFn="offPopup"
    @confirmFn="onSave" Width="480">
    <div v-loading="loading">
      <el-form :model="unitForm" ref="ruleFormRef" label-width="auto" :rules="rules">
        <el-form-item label="单位名称：" prop="packagingUnitName" :error="newError">
          <pb-input v-model.trim="unitForm.packagingUnitName" placeholder="仅支持添加计数类型" @blur="checkName" maxlength="4"
            width="344px"></pb-input>
        </el-form-item>
      </el-form>
    </div>
  </pb-popup>

</template>

<script setup lang="ts">
import { addUnit, setUnit, checkUnitName } from '@/api/Units'
import { createMessage } from "@/Public-UIlibrary/pb-message/method";

const loading = ref(false)
const emits = defineEmits(['refresh'])
const formOrigin = () => ({
  packagingUnitName: null,
  isWeighed: 1,
})
const unitForm = ref(formOrigin())
const rules = reactive(
  {
    packagingUnitName: [{ required: true, message: "此项必填", trigger: ["blur", "change"] }, {
      pattern: /^[\u4E00-\u9FA5A-Za-z]{1,4}$/,
      message: "最多包含1-4位字母或中文",
      trigger: ["blur", "change"],
    },
    {
      validator(rule, value, callback) {
        checkName(value).then(res => {
          if (res) {
            return callback('单位名称已存在')
          } else {
            callback()
          }
        })
      }
    }
    ],
  }
)
const isShow = ref(false)

const showFn = (data) => {
  if (data) {
    unitForm.value = data
  }
  isShow.value = true
}

const offPopup = () => {
  ruleFormRef.value.resetFields();
  unitForm.value = formOrigin();
}

const newError = ref('')
const checkName = (val) => {
  return new Promise<void>((resolve, reject) => {
    let skuPackagingUnitId = unitForm.value.skuPackagingUnitId ? unitForm.value.skuPackagingUnitId : null
    checkUnitName({ skuPackagingUnitName: val, skuPackagingUnitId }).then(res => {
      if (res.code == 2000) {
        if (res.data.skuPackagingUnitNameExist) {
          resolve(true)
        } else {
          resolve(false)
        }
      }
    })
  })

}

const ruleFormRef = ref(null)
const onSave = async () => {
  await ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (unitForm.value.skuPackagingUnitId) {
        setUnitApi()
      } else {
        addUnitApi()
      }
    }
  });
}

const addUnitApi = () => {
  loading.value = true
  return new Promise<void>((resolve, reject) => {
    addUnit(unitForm.value).then(res => {
      loading.value = false
      if (res.code == 2000) {
        createMessage({
          message: '添加成功'
        })
        isShow.value = false
        emits('refresh')
      }
    })
  })
}
const setUnitApi = () => {
  loading.value = true
  return new Promise<void>((resolve, reject) => {
    let { skuPackagingUnitId, packagingUnitName, isWeighed } = unitForm.value
    setUnit({ skuPackagingUnitId, packagingUnitName, isWeighed }).then(res => {
      loading.value = false
      if (res.code == 2000) {
        createMessage({
          message: '编辑成功'
        })
        isShow.value = false
        emits('refresh')
      }
    })
  })
}

defineExpose({ showFn })
</script>

<style lang="scss" scoped></style>